package com.central.apps.handler.until;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

;

/**
 * Created by Ocean lin on 2019/5/15.
 *
 * @author Ocean lin
 */
public class DateUtiles {
    public static final String DATE_PATTERN = "yyyy-MM-dd";
    public static final String DATE_PATTERN_24 = "yyyy-MM-dd HH:mm:ss";
    public static final SimpleDateFormat SimpleDateFormatUtil_24 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    public static String getYmd(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtiles.DATE_PATTERN);
        String format = sdf.format(date);
        return format;
    }

    /**
     * 比较时间是否相等
     *
     * @param date1 时间1
     * @param date2 时间2
     * @return
     */
    public static boolean isSameDay(Date date1, Date date2) {
        if (date1 != null && date2 != null) {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);
            return isSameDay(cal1, cal2);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }

    /**
     * 比较时间是否相等
     *
     * @param cal1
     * @param cal2
     * @return
     */
    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 != null && cal2 != null) {
            return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH) &&
                    cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }


    /**
     * 判断时间是否在起止时间范围内
     *
     * @param nowTime   传入时间
     * @param beginTime 起始时间
     * @param endTime   终止时间
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 日期相加减天数
     *
     * @param date        如果为Null，则为当前时间
     * @param days        加减天数
     * @param includeTime 是否包括时分秒,true表示包含
     * @return
     * @throws ParseException
     */
    public static Date dateAdd(Date date, int days, boolean includeTime) throws ParseException {
        if (date == null) {
            date = new Date();
        }
        if (!includeTime) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtiles.DATE_PATTERN);
            date = sdf.parse(sdf.format(date));
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }


    /**
     * @param date
     * @param hour
     * @param includeTime
     * @return
     * @throws ParseException
     */
    public static Date hourAdd(Date date, int hour, boolean includeTime) {
        if (date == null) {
            date = new Date();
        }
        if (!includeTime) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtiles.DATE_PATTERN_24);
            try {
                date = sdf.parse(sdf.format(date));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, hour);
        return cal.getTime();
    }


    public static Date parseStrToDate(String time) {
        if (null == time || "".equals(time)) {
            return null;
        }

        Date date = null;
        try {
            DateFormat dateFormat = new SimpleDateFormat(DATE_PATTERN_24);
            date = dateFormat.parse(time);
        } catch (Exception e) {

        }
        return date;
    }




    //查询所输入日期是周几
    public static String dayForWeek(String pTime) throws Throwable {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date tmpDate = format.parse(pTime);

        Calendar cal = Calendar.getInstance();

        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};

        try {

            cal.setTime(tmpDate);

        } catch (Exception e) {

            e.printStackTrace();

        }

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。

        if (w < 0)

            w = 0;

        return weekDays[w];

    }

    /**
     * 获取当前日期是本月的第几周(通过本月有几个周三来判断)
     *
     * @param dateStr 日期(格式：yyyy-MM-dd)
     * @return 第n周
     * @throws Exception
     */

    public static int getWeekByWed(String dateStr) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式

        Date date = sdf.parse(dateStr);

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了

        int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天

        if (1 == dayWeek) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);

        }

        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一

        calendar.setFirstDayOfWeek(Calendar.MONDAY);

        // 获得当前日期是一个星期的第几天

        int day = calendar.get(Calendar.DAY_OF_WEEK);

        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值，变为周一

        calendar.add(Calendar.DATE, calendar.getFirstDayOfWeek() - day);

        calendar.add(Calendar.DATE, 2);// 加两天变为周三

        //得到传入日期所在周的周三

        String wed = sdf.format(calendar.getTime());

        // 本月份的天数

        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        int wek = 3;//判断是周三

        int index = 0;//本月的第几个周三

        List list = new ArrayList();

        for (int i = 1; i <= days; i++) {
            calendar.set(Calendar.DAY_OF_MONTH, i);

            int weekd = calendar.get(Calendar.DAY_OF_WEEK) - 1;// 注意,Calendar对象默认星期天为1

            if (weekd == wek) {
                String aaa = sdf.format(calendar.getTime());

                list.add(aaa);

                if (wed.equals(aaa)) {
                    index = list.size();

                }

            }

        }

        return index;

    }

    /**
     * 在原有的时间上添加几个月
     *
     * @param sourceDate 原有时间
     * @param month      几个月
     * @return
     */
    public static Date stepMonth(Date sourceDate, int month) {
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.MONTH, month);

        return c.getTime();
    }

    /**
     * 在原有的时间上添加几天
     *
     * @param sourceDate 原有时间
     * @param day      几个天
     * @return
     */
    public static Date stepDay(Date sourceDate, int day) {
        Calendar c = Calendar.getInstance();
        c.setTime(sourceDate);
        c.add(Calendar.DAY_OF_MONTH, day);

        return c.getTime();
    }

    /**
     * 在原有的时间上添加几分钟
     *
     * @param sourceDate 原有时间
     * @param minute      几个分钟
     * @return
     */
    public static Date stepMinute(Date sourceDate, int minute) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.setTime(sourceDate);
        nowTime.add(Calendar.MINUTE, minute);//几分钟后的时间

        return nowTime.getTime();
    }
    /**
     * 在原有的时间上添加几小时
     *
     * @param sourceDate 原有时间
     * @param minute      几个小时
     * @return
     */
    public static Date stepHour(Date sourceDate, int minute) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.setTime(sourceDate);
        nowTime.add(Calendar.HOUR, minute);//几小时后的时间
        return nowTime.getTime();
    }

    /**
     * 数字转周几大写
     *
     * @param number 数字
     */
    public static String numberToWeek(int number) {
        String week = "";
        if (number != 0 && number < 8) {
            switch (number) {
                case 1:
                    week = "星期一";
                    break;
                case 2:
                    week = "星期二";
                    break;
                case 3:
                    week = "星期三";
                    break;
                case 4:
                    week = "星期四";
                    break;
                case 5:
                    week = "星期五";
                    break;
                case 6:
                    week = "星期六";
                    break;
                case 7:
                    week = "星期日";
                    break;
            }
        }
        return week;
    }


//    public static void main(String[] args) throws ParseException {
//        DateTimeFormatter  sdftime3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//
//        String weekAndDays = weekMontoSun(2021,9,1,4);
//        System.out.println(weekAndDays);
//    }

    /**
     * @param year 年份
     * @param month 月份
     * @param weekOfMonth 这个月的第几周
     * @param dayOfWeek 星期几
     * @return
     */
    public static String weekMontoSun(int year, int month, int weekOfMonth, int dayOfWeek){
        Calendar c = Calendar.getInstance();
        c.set(year, month-1, 1); // x年 y月 1号
        int i_week_day = c.get(Calendar.DAY_OF_WEEK); //如果i_week_day =1 的话 实际上是周日
        int weekDay = 0;
        if(i_week_day == 1){ //dayOfWeek+1 就是星期几（星期日 为 1）
            weekDay = (weekOfMonth-1)*7 + dayOfWeek+1;
        }else{
            weekDay = 7-i_week_day+1 + (weekOfMonth-1)*7 + dayOfWeek +1;
        }
        c.set(Calendar.DATE, weekDay); //在当月1号的基础上加上相应的天数
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(c.getTime());
    }


    public static void sleepTaskByIp() throws Exception {
        String localIPList = getLocalIPList();
        localIPList = localIPList.substring(localIPList.length()-1);
        int time = Integer.valueOf(localIPList)*7;
        Thread.sleep(time*1000);
        System.out.println("sleepTime: " + time + "s");
    }

    public static String getLocalIPList() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddresses;
            InetAddress inetAddress;
            String ip;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    inetAddress = inetAddresses.nextElement();
                    if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
                        ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList.get(1);
    }

    /** 比较两个时间相差分钟 */
    public static long calculatetimeGapMins(String startDate, String endDate) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long hour = 0;
        try {
            Date date1, date2;
            date1 = simpleDateFormat.parse(startDate);
            date2 = simpleDateFormat.parse(endDate);
            double millisecond = date2.getTime() - date1.getTime();
            //四舍五入
            hour = Math.round(millisecond / (60 * 1000));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return hour;
    }

}
